package com.jiexin.filter;

import com.jiexin.common.RequestHolder;
import com.jiexin.model.SysUser;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Jay_Liu
 * @Description:
 * @Date: Created in 16:33 2018/4/7 0007
 * @Modified By:
 */
@Slf4j
public class LoginFilter implements Filter {


    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //String servletPath = req.getServletPath();
        SysUser sysUser = (SysUser)req.getSession().getAttribute("user");
        //用户不存在，返回登陆页面
        if (sysUser == null) {
            //signin.jsp不加前缀时，默认是从当前路径下进行调整
            String path = "/signin.jsp";
            resp.sendRedirect(path);
            return;
        }
        //用户存在的话，将当前请求与对象放入ThreadLocal
        RequestHolder.add(sysUser);
        RequestHolder.add(req);
        filterChain.doFilter(servletRequest,servletResponse);
        return;
    }

    public void destroy() {

    }
}
